<template>
	<view class="signin-container">
		<view id="container"></view>

		<view class="content">

			<view class="title">
				{{itemData.activityName}}

			</view>
			<view class="voluteer-name">
				{{itemData.organizationName}}
			</view>
			<view class="time">
				签到时间：{{itemData.beginTime}}
			</view>
			<view class="address">
				签到地点：{{itemData.serviceAddressAddress}}
			</view>


			<view class="btn flex flex-column align-center justify-center text-white text-center" @click="runSignIn">
				<view class="time">{{new Date().getHours().toString().padStart(2, '0')}}:{{new Date().getMinutes().toString().padStart(2, '0')}}</view>
				<view class="text">签到</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
	} from "vue";
	import {
		onShow
	} from "@dcloudio/uni-app"
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import request from '../../api/index.js'

	const itemData = ref({})
	const mapContainer = ref(null);



	const targetLon = ref(0)
	const targetLat = ref(0)

	const myLon = ref(0)
	const myLat = ref(0)

	const isCanSignIn = ref(false)

	var map, circle, soianWX;

	const initMap = (lon, lat) => {
		console.log("lon--------", lon)
		console.log("lat--------", lat)
		map = new AMap.Map('container', {
			zoom: 14.6,
			center: [lon, lat],
			resizeEnable: true
		});




		// 创建点覆盖物
		const targetMarker = new AMap.Marker({
			position: new AMap.LngLat(lon, lat),
			icon: new AMap.Icon({
				image: 'http://it.jushi.com/volunteerH5/static/icon/targetPos.png',
				size: new AMap.Size(32, 32), // 设置图标大小
				imageSize: new AMap.Size(32, 32) // 设置图标图像大小
			}),
			draggable: false, // 设置不可拖动
			anchor: 'bottom-center' // 设置图标底部居中
		});



		map.add(targetMarker);

		// 初始化圆形
		const center = [lon, lat]; // 假设这是圆心的经纬度
		initCircle(center);

	};

	// 初始化圆形
	const initCircle = (center) => {
		console.log("center------", center)
		let circle = new AMap.Circle({
			center: center,
			anchor: 'bottom-center',
			radius: 1000, // 半径 1000 米
			borderWeight: 3,
			strokeColor: '#1791fc',
			strokeOpacity: 1,
			strokeWeight: 1,
			fillOpacity: 0.4,
			strokeStyle: 'dashed',
			strokeDasharray: [10, 10],
			fillColor: '#1791fc',
			zIndex: 50,
			visible: true
		});

		map.add(circle);
	};











	onShow(() => {
		console.log('123')

	})



	onLoad((options) => {
		itemData.value = JSON.parse(options.data)
		targetLon.value = +(itemData.value.longitude)
		targetLat.value = +(itemData.value.latitude)

	})




	const getJsapiTicket = (url, type) => {



		request({
			url: '/api/wx/work/core/wx-config',
			method: 'GET',
			data: {
				url: url
			}

		}, e => {
			if (e.success) {
				const data = e.data
				const appId = data.appId
				const timestamp = data.timestamp
				const nonceStr = data.nonceStr
				const signature = data.signature
				console.log("e.data========", e.data)
				console.log("type========", type)

				runAuth(appId, timestamp, nonceStr, signature)



			} else {
				// uni.showToast({
				// 	title: e.errorMessage,
				// 	icon: 'error'
				// })
			}

		})
	}


	const runAuth = (appId, timestamp, nonceStr, signature) => {

		jWeixin.config({
			// 必须这么写，否则wx.invoke调用形式的jsapi会有问题
			beta: true,
			// 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印
			debug: false,
			// 必填，企业微信的corpID，必须是本企业的corpID，不允许跨企业使用
			appId: appId,
			timestamp: timestamp, // 必填，生成签名的时间戳
			nonceStr: nonceStr, // 必填，生成签名的随机串
			signature: signature, // 必填，签名
			// 必填，需要使用的JS接口列表，凡是要调用的接口都需要传进来
			jsApiList: ["getLocation"],
			success: function(res) {

				alert("res===" + JSON.stringify(res));

			},
			fail: function(res) {
				// alert("fail=========", JSON.stringify(res));
				if (res.errMsg.indexOf('function not exist') > -1) {
					alert('版本过低请升级');
				}
			}

		});


		jWeixin.ready(function() {
			// wx.showLoading({ //显示加载
			// 	title: '定位中...',
			// 	mask: true,
			// })

			getLocation()


		});
		jWeixin.error(function(res) {
			wx.hideLoading();
			alert('失败' + JSON.stringify(res));

		});

	}




	// jWeixin
	const getLocation = () => {
		jWeixin.getLocation({
			type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
			success: function(res) {
				// alert("res" + JSON.stringify(res))
				myLon.value = res.longitude
				myLat.value = res.latitude

				// 创建点覆盖物
				const myMarker = new AMap.Marker({
					position: new AMap.LngLat(myLon.value, myLat.value),
					icon: new AMap.Icon({
						image: 'http://it.jushi.com/volunteerH5/static/icon/myPos.png',
						size: new AMap.Size(32, 32), // 设置图标大小
						imageSize: new AMap.Size(32, 32) // 设置图标图像大小
					}),
					draggable: false, // 设置不可拖动
					anchor: 'bottom-center' // 设置图标底部居中
				});



				map.add(myMarker);
				let p1 = [myLon.value, myLat.value]
				let p2 = [targetLon.value, targetLat.value]
				let dis = AMap.GeometryUtil.distance(p1, p2);
				console.log("dis-------", dis);
				isCanSignIn.value = dis < 2000
				wx.hideLoading();

			},
			fail: function(err) {
				alert("err" + JSON.stringify(err))
			}
		});
	}





	const runSignIn = () => {
		if (!isCanSignIn.value) {
			uni.showToast({
				title: '不在该范围内！',
				icon: 'error'
			})
			return
		}

		uni.showLoading({
			title: '签到中',
			mask: true
		});
		request({
			url: '/api/volunteer/activity-bd/activity-bd-update',
			method: 'POST',
			data: {
				status: '4',
				activityId: itemData.value.id
			}
		}, e => {
			if (e.success) {
				console.log('e-------------', e)
				uni.showToast({
					title: '签到成功',
					icon: 'success'
				})
				uni.navigateBack(-1);
			} else {
				uni.showToast({
					title: e.errorMessage,
					icon: 'success'
				})
			}
			uni.hideLoading()
		})
	}

	async function loadJweixin() {
		const script = document.createElement('script');
		script.src = 'https://res.wx.qq.com/open/js/jweixin-1.2.0.js';
		document.head.appendChild(script);
		await new Promise(resolve => setTimeout(resolve, 1000)); // 等待脚本加载完成
	}

	onMounted(() => {
		initMap(targetLon.value, targetLat.value)
		loadJweixin()
		const url = window.location.href.split('#')[0]
		console.log("url-----------", url);
		getJsapiTicket(url);
	})
</script>

<style lang="scss" scoped>
	.signin-container {
		// position: relative;
	}

	#container {
		width: 100%;
		height: 100vh;

	}

	.content {
		width: 94%;
		height: 500rpx;
		padding: 24rpx;
		box-sizing: border-box;
		background-color: #fff;
		position: absolute;
		bottom: 42rpx;
		border-radius: 8rpx;
		left: 50%;
		transform: translateX(-50%);

		.btn {
			position: absolute;
			right: 0;
			bottom: 0;
		}

		.title {
			font-family: PingFang SC;
			font-weight: bold;
			font-size: 28rpx;
			color: #333333;
			margin-bottom: 12rpx;
		}

		.voluteer-name,
		.time,
		.address {
			font-size: 24rpx;
			margin-top: 12rpx;
		}

		.btn {
			position: absolute;
			width: 180rpx;
			height: 180rpx;
			left: 50%;
			bottom: 42rpx;
			transform: translateX(-50%);
			background: linear-gradient(0deg, #505FFF 0%, #A3ABFF 100%);
			border-radius: 50%;

			.time {
				margin-bottom: 3rpx;
			}

			.text {
				font-size: 32rpx;
				margin-top: 3rpx;
			}
		}
	}
</style>